package com.house365.core.helper;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.widget.Toast;

import com.house365.core.R;
import com.house365.core.application.BaseApplication;
import com.house365.core.bean.VersionInfo;
import com.house365.core.constant.CorePreferences;
import com.house365.core.http.HttpAPIAdapter;
import com.house365.core.util.DeviceUtil;
import com.house365.core.util.FileUtil;
import com.house365.core.view.LoadingDialog;

public class VersionUpgradeHelper {

	public Context context = null;
	protected LoadingDialog tloadingDialog;
	private ProgressDialog progressDialog;
	private static boolean isCannel = false;

	private AlertDialog alertDialog, alertUpdateDialog;
	private BaseApplication<HttpAPIAdapter> mApplication;

	private VersionInfo currVersion;
	private VersionInfo newVersion;
	private static VersionUpgradeHelper VersionUpgradeHelper = null;

	public VersionUpgradeHelper(Context context) {
		this.context = context;
		mApplication = (BaseApplication<HttpAPIAdapter>) context.getApplicationContext();
	}
	
	private void initData() {
		// ��ʼ������
		isCannel = false;
	}
	public interface VersionUpgradeListener{
		public void onPreGetVersion();
		public void onGetedVersion();
	}
	/**
	 * �ֶ�������
	 */
	public void checkAndUpdateByHand() {
		if (DeviceUtil.isNetConnect(context)) {
			//给提示框，
			
			if (needUpdate()) {
				showUpdateDialog();
			} else {
				notNewVersionShow();
			}
		} else {
			Toast.makeText(context, R.string.net_error, Toast.LENGTH_SHORT)
					.show();
			return;
		}
	}
	public void checkAndUpdateByHand(VersionUpgradeListener versionUpListener) {
		if (DeviceUtil.isNetConnect(context)) {
			//给提示框，
			versionUpListener.onPreGetVersion();
			boolean needUpdate = needUpdate();
			versionUpListener.onGetedVersion();
			if (needUpdate) {
				showUpdateDialog();
			} else {
				notNewVersionShow();
			}
		} else {
			Toast.makeText(context, R.string.net_error, Toast.LENGTH_SHORT)
					.show();
			return;
		}
	}
	/**
	 * �Զ�������
	 */
	public void checkAndUpdateByAuto() {
		if (DeviceUtil.isNetConnect(context)) {
			if (needUpdate()) {
				showUpdateDialog();
			}
		}
	}

	// ��ȡ�汾��Ϣ
	public void getVerInfo() {
		currVersion = getCurrentVersion();
		newVersion = getServerVerCode();
	}

	/**
	 * ��ȡ���°汾
	 */
	private VersionInfo getServerVerCode() {
		try {
			return mApplication.getApi().getAppNewVersion();
		} catch (Exception e) {
			CorePreferences.ERROR(e.getMessage());
			return null;
		}
	}

	/**
	 * ����ǲ�����Ҫ����
	 * 
	 * @return
	 */
	public boolean needUpdate() {
		// 应该有三种结果：要更新，已是最新不需更新，(网络超时等)版本获取失败
		getVerInfo();
		if (newVersion != null
				&& (newVersion.getVersionCode() > currVersion.getVersionCode())) {
			return true;
		} else {
			return false;
		}
	}
	
	public VersionInfo getNewVersion(){
		return newVersion;
	}

	public void notNewVersionShow() {
		StringBuffer sb = new StringBuffer();
		sb.append(context.getResources().getString(R.string.version_current));
		sb.append(currVersion.versionName);

		sb.append("\n"
				+ context.getResources().getString(
						R.string.version_current_is_newset));
		if (alertDialog == null) {
			AlertDialog.Builder alert = new AlertDialog.Builder(context)
					.setTitle(R.string.version_update_title)
					.setMessage(sb.toString())
					.setPositiveButton(R.string.dialog_button_ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.cancel();
									alertDialog = null;
								}
							});
			alertDialog = alert.create();
			alertDialog.show();
		}
	}

	/**
	 * ������ʾ
	 */
	public void showUpdateDialog() {
		if (alertUpdateDialog == null) {
			String newverStr = context.getResources().getString(
					R.string.version_update_newver, newVersion.versionName);
			final String version_downloading = context.getResources()
					.getString(R.string.version_downloading,
							newVersion.versionName);
			final String installapkfile = CorePreferences.getAppTmpSDPath()
					+ "/" + FileUtil.getFileNameFromUrl(newVersion.apkFileUrl);
			AlertDialog.Builder alert = new AlertDialog.Builder(context)
					.setTitle(newverStr)
					.setMessage(newVersion.getVersionNote())
					.setPositiveButton(R.string.version_update_immediately,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									Downloadhelper dm = new Downloadhelper(
											context, true);
									dm.downLoadFile(version_downloading,
											newVersion.getApkFileUrl(),
											installapkfile);
								}
							})
					.setNegativeButton(R.string.version_cancel,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.cancel();
									alertUpdateDialog = null;
								}
							});

			alertUpdateDialog = alert.create();
		}
		alertUpdateDialog.show();
	}

	/**
	 * ��ȡ��ǰ�汾��Ϣ
	 */
	public VersionInfo getCurrentVersion() {
		try {
			PackageInfo info = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0);
			VersionInfo version = new VersionInfo();
			version.versionCode = info.versionCode;
			version.versionName = info.versionName;
			CorePreferences.DEBUG("��ǰ�汾��" + version.versionCode);
			return version;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}

}
